package org.tech4j.springboot.starter.logging.common.context;

import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.RequestAttributes;

/**
 * @program: tech4j
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/6 15:21
 **/
public abstract class LogContextHolder {
    private static final ThreadLocal<LogAttributes> inheritableLogAttributesHolder =
            new InheritableThreadLocal<>() {
                @Override
                protected LogAttributes initialValue() {
                    return new LogAttributes();
                }
            };

    private static final ThreadLocal<LogAttributes> logAttributesHolder =
            new ThreadLocal<>() {
                @Override
                protected LogAttributes initialValue() {
                    return new LogAttributes();
                }
            };

    public static void resetLogAttributes() {
        logAttributesHolder.remove();
        inheritableLogAttributesHolder.remove();
    }

    public static void setLogAttributes(@Nullable LogAttributes attributes) {
        setLogAttributes(attributes, false);
    }

    public static void setLogAttributes(@Nullable LogAttributes attributes, boolean inheritable) {
        if (attributes == null) {
            resetLogAttributes();
        }
        else {
            if (inheritable) {
                inheritableLogAttributesHolder.set(attributes);
                logAttributesHolder.remove();
            }
            else {
                logAttributesHolder.set(attributes);
                inheritableLogAttributesHolder.remove();
            }
        }
    }

    @Nullable
    public static LogAttributes getLogAttributes() {
        LogAttributes attributes = logAttributesHolder.get();
        if (attributes == null) {
            attributes = inheritableLogAttributesHolder.get();
        }
        return attributes;
    }


}
